package com.gestionabsences.servlets;

import com.gestionabsences.beans.MapStudents;
import com.gestionabsences.beans.ResultRequest;
import com.gestionabsences.beans.WebUser;
import com.gestionabsences.config.DAOFactory;
import com.gestionabsences.database.ToolsRequest;
import com.gestionabsences.form.FormSecretary;
import com.gestionabsences.form.FormSecretaryJustification;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author matt
 */
public class HomeSecretary extends HttpServlet {

    public static final String VUE_HOME = "/WEB-INF/Inc/secretaire/home.jsp";
    
    public static final String ATT_PAGE = "requestedPage";
    public static final String VUE_QUERY = "gui_query.jsp";
    public static final String VUE_REPORT_ABSENCES = "gui_change_justification.jsp";
    public static final String VUE_READ_ME = "readme.jsp";
    
    private static final String ATT_DAO_FACTORY = "daofactory";
    public static final String ATT_SESSION_WEBUSER = "sessionWebuser";
    public static final String ATT_SESSION_LISTE_ETUDIANTS = "listeEtudiants";
    public static final String ATT_SESSION_LISTE_ETUDIANTS_ABSENTS = "listeEtudiantsAbsents";
    
    public static final String ATT_FORM_QUERY = "form";
    public static final String ATT_RESULT_QUERY_ABSENCES = "resultatQueryAbsences";
    
    public static final String ATT_FORM_JUSTIFICATION_CHOIX_ETUDIANT = "formJustificationChoixEtudiant";
    public static final String ATT_RESULT_QUERY_LISTE_ABSENCES = "resultatQueryListAbsences";
    
    public static final String ATT_FORM_JUSTIFICATION_CHOIX_ABSENCE = "formJustificationChoixAbsence";
    public static final String ATT_RESULT_QUERY_ABSENCE_ETUDIANT = "resultatQueryAbsenceEtudiant";
    
    public static final String ATT_FORM_JUSTIFICATION_MODIF_ABSENCE = "formJustificationModifAbsence";
    public static final String ATT_RESULT_QUERY_MODIF_ABSENCE = "resultatQueryModifAbsence";
    
    public static final String ATT_RESULT = "resultatUpdate";
    
    private DAOFactory dao;
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	HttpSession session = request.getSession();
	
	WebUser user = (WebUser) session.getAttribute( ATT_SESSION_WEBUSER );
	
	MapStudents listEtudiants = (MapStudents) session.getAttribute( ATT_SESSION_LISTE_ETUDIANTS );
	if(listEtudiants == null) {
	    listEtudiants = creerListeEtudiants();
	    session.setAttribute(ATT_SESSION_LISTE_ETUDIANTS, listEtudiants);
	}
	
	MapStudents listEtudiantsAbsents = (MapStudents) session.getAttribute( ATT_SESSION_LISTE_ETUDIANTS_ABSENTS );
	if(listEtudiantsAbsents == null) {
	    listEtudiantsAbsents = creerListeEtudiantsAbsents();
	    session.setAttribute(ATT_SESSION_LISTE_ETUDIANTS_ABSENTS, listEtudiantsAbsents);
	}
	
	String page = request.getParameter( "page" );
	
	if (page != null && listEtudiants != null) {
	    if (page.compareTo("report") == 0) {
		request.setAttribute(ATT_PAGE, VUE_REPORT_ABSENCES);
	    } else if (page.compareTo("query") == 0) {
		request.setAttribute(ATT_PAGE, VUE_QUERY);
	    } else {
		request.setAttribute(ATT_PAGE, VUE_READ_ME);
	    }
	} else {
	    request.setAttribute(ATT_PAGE, VUE_READ_ME);
	}
	
	this.getServletContext().getRequestDispatcher( VUE_HOME ).forward( request, response );
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	HttpSession session = request.getSession();
	
	WebUser user = (WebUser) session.getAttribute( ATT_SESSION_WEBUSER );
	
	MapStudents listEtudiants = (MapStudents) session.getAttribute( ATT_SESSION_LISTE_ETUDIANTS );
	if(listEtudiants == null) {
	    listEtudiants = creerListeEtudiants();
	    session.setAttribute(ATT_SESSION_LISTE_ETUDIANTS, listEtudiants);
	}
	
	MapStudents listEtudiantsAbsents = (MapStudents) session.getAttribute( ATT_SESSION_LISTE_ETUDIANTS_ABSENTS );
	if(listEtudiantsAbsents == null) {
	    listEtudiantsAbsents = creerListeEtudiantsAbsents();
	    session.setAttribute(ATT_SESSION_LISTE_ETUDIANTS_ABSENTS, listEtudiantsAbsents);
	}
	
	String page = request.getParameter( "page" );
	
	if (page != null && listEtudiants != null) {
	    if (page.compareTo("report") == 0) {
		request.setAttribute(ATT_PAGE, VUE_REPORT_ABSENCES);
		
		System.out.println( request.toString() );
		
		if( request.getParameter(FormSecretaryJustification.CHAMP_STUDENT ) != null ) {
		    FormSecretaryJustification formChoixEtudiant = new FormSecretaryJustification(dao, listEtudiantsAbsents);
		    ResultRequest resReq = formChoixEtudiant.recuperationListeAbsences(request);
		    
		    request.setAttribute( ATT_FORM_JUSTIFICATION_CHOIX_ETUDIANT, formChoixEtudiant);
		
		    if (formChoixEtudiant.getErreurs().isEmpty()) {
			if (resReq != null) {
			    request.setAttribute(ATT_RESULT_QUERY_LISTE_ABSENCES, resReq);
			}
		    }
		} else if ( request.getParameter(FormSecretaryJustification.CHAMP_NUM_TUPLE ) != null ) {
		    FormSecretaryJustification formChoixAbsences = new FormSecretaryJustification(dao, listEtudiantsAbsents);
		    ResultRequest resReq = formChoixAbsences.recuperationAbsence(request);
		    
		    request.setAttribute(ATT_FORM_JUSTIFICATION_CHOIX_ABSENCE, formChoixAbsences);
		    
		    if (formChoixAbsences.getErreurs().isEmpty()) {
			if (resReq != null) {
			    request.setAttribute(ATT_RESULT_QUERY_ABSENCE_ETUDIANT, resReq);
			}
		    } else {
			System.out.println( formChoixAbsences.getErreurs().toString() );
		    }
		} else if ( request.getParameter(FormSecretaryJustification.CHAMP_CREDIBILITE) != null ) {
		    FormSecretaryJustification formModificationAbsence = new FormSecretaryJustification(dao, listEtudiantsAbsents);
		    boolean updateDone = formModificationAbsence.recupEtModifJustification(request);
		    
		    request.setAttribute(ATT_FORM_JUSTIFICATION_MODIF_ABSENCE, formModificationAbsence);
		    
		    if (formModificationAbsence.getErreurs().isEmpty()) {
			if (updateDone) {
			    request.setAttribute(ATT_RESULT, "L'absence a bien été modifiée.");
			} else {
			    request.setAttribute(ATT_RESULT, "Échec de la modification de l'absence.");
			}
		    }
		}
		
	    } else if (page.compareTo("query") == 0) {
		request.setAttribute(ATT_PAGE, VUE_QUERY);

		FormSecretary form = new FormSecretary(dao, listEtudiants);
		ResultRequest resReq = form.creationResultat(request);

		request.setAttribute(ATT_FORM_QUERY, form);

		if (form.getErreurs().isEmpty()) {
		    if (resReq != null) {
			request.setAttribute(ATT_RESULT_QUERY_ABSENCES, resReq);
		    }
		}
	    }

	} else {
	    request.setAttribute(ATT_PAGE, VUE_READ_ME);
	}

	this.getServletContext().getRequestDispatcher(VUE_HOME).forward(request, response);
    }

    private MapStudents creerListeEtudiantsAbsents()
    {
	Connection connexion = null;
	MapStudents listeEtudiantsAbsents = new MapStudents();
	
	String SQL_SELECT_LIST_ETUDIANTS = "SELECT DISTINCT ON(A.ine) A.ine, E.nom, E.prenom FROM Absence A, Etudiant E WHERE A.ine = E.ine;";
	
	try {
	    connexion = dao.getConnection();
	    
	    PreparedStatement preparedStatement = null;
	    ResultSet resultSet = null;
	
	    try {
		preparedStatement = ToolsRequest.prepareRequest( connexion, SQL_SELECT_LIST_ETUDIANTS, false);
		System.out.println( preparedStatement.toString() );
		resultSet = preparedStatement.executeQuery();
		
		String ine;
		String nom;
		String prenom;
		while ( resultSet.next() ) {
		    ine = resultSet.getString( "ine" );
		    nom = resultSet.getString( "nom" );
		    prenom = resultSet.getString( "prenom" );
		    
		    System.out.println("INE = " + ine + " " + prenom + " " + nom);
		    
		    listeEtudiantsAbsents.put( ine, prenom + " " + nom );
		}		
	    } catch(SQLException e) {}
	    finally {
		ToolsRequest.close(preparedStatement, resultSet);
	    }
	    
	} catch (SQLException e) {}
	finally {
	    ToolsRequest.close(connexion);		
	}
	
	return listeEtudiantsAbsents;
    }
    
    private MapStudents creerListeEtudiants()
    {
	Connection connexion = null;
	MapStudents listeEtudiants = new MapStudents();
	
	String SQL_SELECT_LIST_ETUDIANTS = "SELECT ine, nom, prenom FROM Etudiant;";
	
	try {
	    connexion = dao.getConnection();
	    
	    PreparedStatement preparedStatement = null;
	    ResultSet resultSet = null;
	
	    try {
		preparedStatement = ToolsRequest.prepareRequest( connexion, SQL_SELECT_LIST_ETUDIANTS, false);
		System.out.println( preparedStatement.toString() );
		resultSet = preparedStatement.executeQuery();
		
		String ine;
		String nom;
		String prenom;
		while ( resultSet.next() ) {
		    ine = resultSet.getString( "ine" );
		    nom = resultSet.getString( "nom" );
		    prenom = resultSet.getString( "prenom" );
		    
		    System.out.println("INE = " + ine + " " + prenom + " " + nom);
		    
		    listeEtudiants.put( ine, prenom + " " + nom );
		}		
	    } catch(SQLException e) {}
	    finally {
		ToolsRequest.close(preparedStatement, resultSet);
	    }
	    
	} catch (SQLException e) {}
	finally {
	    ToolsRequest.close(connexion);		
	}
	
	return listeEtudiants;
    }
    
    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
	return "Servlet de l'espace Secrétaire ";
    }// </editor-fold>
    
    @Override
    public void init() throws ServletException {
	dao = (DAOFactory) getServletContext().getAttribute(ATT_DAO_FACTORY);
    }
}
